<template>
	<view class="paidDetail">
		<nav-bars backState="1000" :bgColor="navBackground" fontColor="#fff" title="选择退货商品"></nav-bars>
		<view class="topImg">
			<image :src="`${baseImg}/static/adminShop/detailBack.png`" mode=""></image>
			<!-- 退款说明 -->
			<view class="userInfo">
				<view class="infoItem">
					<view class="left">
						<view class="call">
							<view class="info">
								<view class="back-dot"></view>
								<text>如有多件商品需要退货，请一并提交申请</text>
							</view>
							<view class="info">
								<view class="back-dot"></view>
								如订单已使用优惠券，部分商品退货优惠券不返还
							</view>
							<view class="info">
								<view class="back-dot"></view>
								如遇订单拆分，部分订单申请退货优惠券不返还
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="content" :style="'margin-top:'+navHeight+'rpx;'">
			<!-- 商品清单 -->
			<view class="shopList">
				<h3>{{orderdetail.store_name}}<i class="iconfont icon-more"></i></h3>
				<view class="list" v-for="(items,index) in orderdetail.list" :key="index">
					<view class="item">
						<view class="left">
							<view class="selectSendOk" :class="{'sendActive':product[index].checked}"
								@click="toSelect(index)">
								<u-icon size="24" name="checkmark"></u-icon>
							</view>
						</view>
						<image :src="items.main_imgurl" mode=""></image>
						<view class="shopInfo">
							<view class="top">
								<view class="tit omit-2">
									{{items.product_title}}
								</view>
								¥ {{items.price}}
							</view>
							<view class="spec">
								<view v-for="(attr_params,index) in items.attr_params" style="display: inline-block;">
									<text v-if="attr_params.attr_name">{{attr_params.attr_value}}</text>
									<text v-if="attr_params.key">{{attr_params.value}}</text>
								</view>
								<text style="float: right;">x{{items.num}}</text>
							</view>
						</view>
					</view>
					<view class="refund-list">
						<view class="all">
							退货数量
							<view class="c_ccart_nums">
								<view class="c_cnMinus" @click="minusCart(items.num,index)"></view>
								<view class="c_cncart_num" v-model="product[index].refund_num">{{product[index].refund_num}}</view>
								<view class="c_cnAdd" @click="addCart(items.num,index)"></view>
							</view>
						</view>
						<view class="all">
							退款原因<text>*</text>
							<view class="uni-list">
								<view class="uni-list-cell">
									<view class="uni-list-cell-db">
										<picker @change="bindPickerChange" :id="index"
											:value="productCopy[index].refund_index" :range="refundCause">
											<view class="uni-input">{{refundCause[productCopy[index].refund_index]}}
											</view>
										</picker>
									</view>
								</view>
							</view>
							<view class="iconfont icon-more"></view>
						</view>
						<view class="all">
							退货方式<span style="color: #9B9B9B;">自行寄回</span>
						</view>
						<view class="need">
							退款金额<text>*</text>
							<span v-if="items.set_deposit_status!=1">¥ {{items.price}}</span>
							<span v-else>¥ {{items.pay_price}}</span>
						</view>
						<view class="message" v-if="items.set_deposit_status===1">不可修改，最多￥{{items.pay_price}}，含发货邮费￥0.00</view>
						<view class="message" v-else>不可修改，最多￥{{items.price}}，含发货邮费￥0.00</view>
						<view class="replenish">
							<view class="title">补充描述</view>
							<textarea class="msg" placeholder-style="font-size: 22rpx;"
								placeholder="补充描述，有助于商家更好的处理售后问题" v-model="product[index].refund_desc" />
						</view>
						<view class="imgBox">
							<view class="item" v-for="(item,indexs) in upImgList" :key="indexs"
								v-if="item.index===index">
								<image class="imagePath" :src="item.image_path" mode=""></image>
								<image class="delImg" @click="delImg(indexs)"
									:src="`${baseImg}/static/adminShop/delImg.png`" mode=""></image>
							</view>
							<view class="upImg" @click="upImg(index)">
								<image :src="`${baseImg}/static/adminShop/camare.png`" mode=""></image>
								上传凭证
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="btn-submit" @click="aftersaleApply">
				提交
			</view>
		</view>

	</view>
</template>

<script>
	import countdown from "@/components/cz-countdown/cz-countdown.vue"
	import service_mall from '@/service/mall.js'
	import aftersale from '@/service/afterSale.js'
	const qrCode = require('@/utils/weapp-qrcode.js')
	import URL from '@/config/url.js'
	export default {
		components: {
			countdown,
			// #ifdef MP-WEIXIN
			"cell": "plugin://contactPlugin/cell",
			// #endif
		},
		data() {
			return {
				navBackground: '',
				baseImg: 'https://manager.ryz1620.com',
				navHeight: 200,
				startTime: '',
				enTime: '',
				orderdetail: {},
				tapIndex: '',
				code: '',
				showModal: false,
				terminal: "",
				config_id: '',
				config_url: '',
				pouchatshow: false,
				refundCause: ['请选择原因', '不想要了/不喜欢', '商品与描述不符', '卖家发错货', '假冒品牌', '其他'],
				upImgList: [],
				store_id: '', //店铺id
				refund_type: '', //申请类型 1退款，2换货，3退款退货
				product: [],
				productCopy: [],

			}
		},
		filters: {
			formatDates(value) {
				let date = new Date(parseInt(value) * 1000);
				let y = date.getFullYear();
				let m = date.getMonth() + 1;
				m = m < 10 ? "0" + m : m;
				let d = date.getDate();
				d = d < 10 ? "0" + d : d;
				let h = date.getHours();
				h = h < 10 ? "0" + h : h;
				let minute = date.getMinutes();
				let second = date.getSeconds();
				minute = minute < 10 ? "0" + minute : minute;
				second = second < 10 ? "0" + second : second;
				return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
			},
			formatDate(value) {
				var date = new Date(value);
				//date.setTime(value);
				var month = date.getMonth() + 1;
				var hours = date.getHours();
				if (hours < 10)
					hours = "0" + hours;
				var minutes = date.getMinutes();
				if (minutes < 10)
					minutes = "0" + minutes;
				var time = date.getFullYear() + "/" + month + "/" + date.getDate() +
					" " + hours + ":" + minutes;
				return time;
			}
		},
		onLoad(options) {
			this.$utils.getUrl()
			this.navHeight = 348 - (Number(this.$store.state.system.navBarHeight) * 2)
			this.order_code = options.order_code
			this.refund_type = options.type
			this.getdata();
			//#ifdef MP-WEIXIN
			this.terminal = "wxapplet";
			//#endif
		},
		methods: {
			copy(value) {
				uni.setClipboardData({
					data: value, //要被复制的内容
					success: () => { //复制成功的回调函数
						console.log('复制成功')
					}
				});
			},
			// 订单详情
			getdata() {
				uni.showLoading()
				service_mall.getdata({
						order_code: this.order_code
					})
					.then(res => {
						uni.hideLoading()
						if (res.code == 1) {
							let endata = res.data.create_time + 86340
							this.startTime = this.$options.filters.formatDate(new Date())
							this.enTime = this.$options.filters.formatDates(endata)
							this.orderdetail = res.data
							var result = [];
							var checked=false;
							res.data.list.forEach(item => {
								if(item.num==1){
									checked=true;
								}
								let data = {
									refund_num: item.num,
									refund_desc: '',
									refund_img: [],
									product_id: item.product_id,
									refund_msg: '', //退款原因
									refund_index: 0,
									checked: checked,
								};
								result.push(data)
							})
							result.map(item => item.checked = checked)
							this.product = result
							this.productCopy = result
							this.gitConfig()
							this.gitwxConfig()
						}
					})
					.catch(err => {
						uni.hideLoading()
					})
			},
			// 获取企业微信callme配置
			gitConfig() {
				service_mall.getCallMeConfig({
					partner_type: 'shop',
					partner_id: this.orderdetail.store_id
				}).then(res => {
					if (res.code == 1) {
						this.config_id = res.data.config_id;
					}
				});
			},
			gitwxConfig() {
				service_mall.getwxMeConfig({
					partner_type: 'shop',
					partner_id: this.orderdetail.store_id
				}).then(res => {
					if (res.code == 1) {
						this.config_url = res.data.url;
					}
				});
			},
			gitpouchatshow() {
				this.pouchatshow = true
			},
			wxCodeClick() {
				this.pouchatshow = false
			},
			gitwxchat() {
				wx.openCustomerServiceChat({
					extInfo: {
						url: this.config_url
					},
					corpId: this.$env.CORPID,
					success(res) {}
				})
			},
			gitchat() {
				uni.showToast({
					title: '哎呀!不好意思，暂未配置客服...',
					icon: 'none',
					duration: 2000
				});
				// uni.navigateTo({
				// 	url: '/pages_customer/pages/index?partner_type=shop&partner_id=' + this.orderdetail.store_id
				// })
			},
			// 确认收货
			confirms(item, id) {
				uni.navigateTo({
					url: "/pages_mall/pages/mall/order/confirmorder?orderid=" + id
				})
			},
			// 选择支付方式
			payModel(item, id) {
				let itemList = ["微信支付", "线下支付"]
				this.itemList = itemList
				uni.showActionSheet({
					itemList: this.itemList,
					success: (t) => {
						this.tapIndex = t.tapIndex + 1
						this.getpayorder(item.order_code)
					}
				});
			},
			initQrCode: function() {
				new qrCode('myQrcode', {
					text: this.code,
					width: 160,
					height: 160,
					colorDark: "#333333",
					colorLight: "#FFFFFF",
					correctLevel: qrCode.CorrectLevel.H
				})
			},
			handleShowCodeClick: function() {
				this.showModal = true
				this.$nextTick(function() {
					this.initQrCode()
				})
			},
			handleHideCodeClick: function() {
				this.showModal = false
			},
			getpayorder(order_codes) {
				service_mall.getpay({
					order_no: order_codes,
					type: 'product_order',
					pay_type: this.tapIndex
				}).then(res => {
					if (res.code == 1) {
						let data = res.data
						if (this.tapIndex == 1) {
							if (this.terminal == 'wxapplet') {
								uni.requestPayment({
									appId: res.data.appId,
									nonceStr: res.data.nonceStr,
									package: res.data.package,
									paySign: res.data.paySign,
									signType: res.data.signType,
									timeStamp: res.data.timeStamp,
									success: (suc) => {
										uni.navigateTo({
											url: "/pages_mall/pages/mall/order/sucess?type=1" +
												'&order_no=' + order_codes
										})
									},
									fail: (err) => {
										uni.navigateTo({
											url: "/pages_mall/pages/mall/order/sucess?type=0" +
												'&order_no=' + order_codes
										})
									}
								});
							} else {
								uni.requestPayment({
									provider: 'wxpay',
									orderInfo: {
										"appid": res.data.appid,
										"partnerid": res.data.partnerid,
										"prepayid": res.data.prepayid,
										"noncestr": res.data.noncestr,
										"package": res.data.package,
										"timestamp": res.data.timestamp,
										"sign": res.data.sign,
									},
									success: (suc) => {
										uni.navigateTo({
											url: "/pages_mall/pages/mall/order/sucess?type=1" +
												'&order_no=' + order_codes
										})
									},
									fail: (err) => {
										uni.navigateTo({
											url: "/pages_mall/pages/mall/order/sucess?type=0" +
												'&order_no=' + order_codes
										})
									}
								});
							}
						} else {
							this.code = res.data.verificationCode
							this.handleShowCodeClick()
						}

					} else {
						this.failMsg(res)
					}
				})
			},
			// 删除订单
			deleteOrder(id) {
				let that = this
				uni.showModal({
					title: "提示！",
					content: "是否删除该订单",
					success: function(i) {
						if (i.confirm) {
							uni.showLoading('正在删除...')
							service_mall.getdelProductOrder({
								order_code: id,
							}).then(res => {
								uni.hideLoading();
								if (res.code == 1) {
									uni.navigateTo({
										url: '/pages_mine/pages/mall/order/list',
									});
								} else {
									uni.showToast({
										title: "删除失败！",
										icon: "none"
									});
								}
							});
						}
					}
				});
			},
			// 取消订单
			cancelOrder(id) {
				let that = this
				uni.showModal({
					title: "提示！",
					content: "是否取消该订单",
					success: function(i) {
						if (i.confirm) {
							uni.showLoading('正在取消...')
							service_mall.getupOrdercancel({
								order_code: id,
							}).then(res => {
								uni.hideLoading();
								if (res.code == 1) {
									that.list = []
									that.page = 1
									that.getdata();
								} else {
									uni.showToast({
										title: "取消失败！",
										icon: "none"
									});
								}
							});
						}
					}
				});
			},
			// 添加商品
			addCart(num, index) {
				if(num==this.product[index].refund_num){
					this.$common.errorToShow('已超出退款数量')
					return false;
				}
				 this.product[index].refund_num++;
			},
			// 删减商品
			minusCart(num, index) {
				if(this.product[index].refund_num==1){
					this.$common.errorToShow('数量不能小于1')
					return false;
				}
				 this.product[index].refund_num--;
			},
			// 删除图片
			delImg(index) {
				this.upImgList.splice(index, 1)
			},
			// 上传图片
			upImg(index) {
				if (this.upImgList.length > 6) {
					uni.showToast({
						title: '上传图片已达上限!',
						icon: 'none'
					})
					return false;
				}
				uni.chooseImage({
					count: 1,
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						uni.uploadFile({
							url: URL.ENTER_UPLOAD_IMAGE,
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'user': 'test'
							},
							success: (uploadFileRes) => {
								uni.showLoading({
									title: '上传中'
								})
								let data = JSON.parse(uploadFileRes.data)
								if (data.code == 1) {
									let obj = {
										img_id: data.data.id,
										image_path: data.data.url,
										index: index,
									}
									this.upImgList.push(obj)
									let product = this.product;
									product[index].refund_img.push(obj.img_id);
									uni.showToast({
										title: '上传成功',
										icon: 'success'
									})
								} else {
									uni.showToast({
										title: data.msg,
										icon: 'none'
									})
								}
								setTimeout(function() {
									uni.hideLoading()
								}, 500)
							}
						});
					}
				});
			},
			bindPickerChange: function(e) {
				let productCopy = this.productCopy;
				let id = e.target.id;
				productCopy[id].refund_index = e.target.value;
			},
			//申请售后
			aftersaleApply() {
				let product = this.product;
			    var result = [];
				var refund_msg = '';
				product.forEach(item => {
					if (item.checked === true) {
						let data = {
							refund_num: item.refund_num,
							refund_desc: item.refund_desc,
							refund_img: item.refund_img.toString(),
							product_id: item.product_id,
							refund_msg: this.refundCause[item.refund_index], //退款原因
						};
						if (item.refund_index == 0) {
							refund_msg = 0;
						}
						result.push(data)
					}
				})
				if(result.length<=0){
					this.$common.errorToShow('请勾选申请售后商品')
					return false;
				}
				if(refund_msg===0){
					this.$common.errorToShow('请选择退款原因')
					return false;
				}
				console.log(result)
				uni.showLoading()
				aftersale.aftersaleApply({
						product: result,
						refund_type: this.refund_type,
						store_id: this.orderdetail.store_id,
						order_code: this.orderdetail.order_code,
						user_id: uni.getStorageSync('userId'),
					})
					.then(res => {
						uni.hideLoading()
						let _this =this;
						if (res.code == 1) {
							_this.$common.errorToShow('提交成功等待商家审核')
                            //跳转售后列表
							setTimeout(function(){
								_this.$common.navigateTo('/pages_mall/pages/mall/after_sale/list?status=0');
							},3000)
						}else{
							_this.$common.errorToShow(res.msg)
						}
					})
					.catch(err => {
						uni.hideLoading()
					})
			},
			// 单个选中
			toSelect(index) {
				if (this.product[index].checked) {
					this.product[index].checked = false
				} else {
					this.product[index].checked = true
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.icon-more {
		display: inline-block;
	}

	.paidDetail {
		width: 100%;

		.topImg {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 348rpx;

			image {
				width: 100%;
				height: 100%;
			}

			.userInfo {
				width: 100%;
				position: absolute;
				left: 0;
				bottom: -78rpx;
				z-index: 200;

				.infoItem {
					padding: 18rpx 16rpx;
					display: flex;
					justify-content: space-between;
					margin: 0 auto;
					width: 702rpx;
					height: 192rpx;
					background-color: #fff;
					border-radius: 16rpx;

					image {
						width: 40rpx;
						height: 40rpx;
					}

					.left {
						display: flex;

						.call {
							margin: 10rpx 20rpx 0 0rpx;
							display: flex;
							flex-direction: column;

							.info {
								margin-bottom: 10rpx;
								display: flex;
								color: #878787;
								font: 500 22rpx/40rpx PingFang SC;
							}

							.back-dot {
								width: 16rpx;
								height: 16rpx;
								margin: 16rpx 16rpx 0 0rpx;
								background: #C3AB7C;
								border-radius: 50%;
							}
						}
					}
				}
			}
		}

		// 内容
		.content {
			padding: 126rpx 24rpx 0;
			margin-bottom: 116rpx;
			padding-bottom: 60rpx;

			// 商品清单
			.shopList {
				background-color: #fff;
				padding: 28rpx;
				border-radius: 16rpx;

				h3 {
					padding-bottom: 28rpx;
					font: 500 30rpx/40rpx PingFang SC;
					color: #0A0605;
				}

				.left {
					margin-right: 24rpx;
					padding-bottom: 24rpx;

					.selectSendOk {
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						width: 36rpx;
						height: 36rpx;
						border-radius: 50%;
						border: 2rpx solid #D8D8D8;
						background-color: #fff;
						color: transparent;
						margin-bottom: 12rpx;
					}

					// 选中
					.sendActive {
						background-color: #DBA954;
						color: #fff;
						border-color: #DBA954;
					}
				}

				.list {
					.item {
						display: flex;
						margin-bottom: 32rpx;

						image {
							width: 148rpx;
							height: 148rpx;
							border-radius: 8RPX;
						}

						.shopInfo {
							width: 478rpx;
							margin-left: 24rpx;
							display: flex;
							flex-direction: column;

							.top {
								color: #505050;
								font: 400 26rpx/40rpx PingFang SC;

								.tit {
									width: 328rpx;
								}

								display: flex;
								justify-content: space-between;
							}

							.spec {
								margin-top: 40rpx;
								color: #A0A0A0;
								font: 400 22rpx/22rpx PingFang SC;
							}
						}
					}
				}

				// 价钱
				.refund-list {
					padding-top: 32rpx;
					border-top: 2rpx solid #F5F5F5;

					.all {
						display: flex;
						justify-content: space-between;
						padding: 10rpx 0;
						font: 400 26rpx/40rpx PingFang SC;
						color: #505050;

						text {
							margin-right: auto;
							color: red;
						}
					}

					.need {
						display: flex;
						justify-content: space-between;
						padding: 10rpx 0;
						font: 500 26rpx/40rpx PingFang SC;
						color: #0A0605;

						text {
							margin-right: auto;
							color: red;
						}

						span {
							color: #DBA954;
						}
					}

					.message {
						display: block;
						font-size: 22rpx;
						color: #9E9E9E;
					}

					.replenish {
						margin: 60rpx 0 20rpx 0;

						.msg {
							margin-top: 16rpx;
							height: 100rpx;
						}
					}

					.c_ccart_nums {
						height: 48rpx;
						display: flex;
						position: relative;
						margin-right: -14rpx;

						//background-color: #007AFF;
						.c_cncart_num {
							width: 72rpx;
							height: 48rpx;
							line-height: 48rpx;
							text-align: center;
							border-radius: 8rpx;
							background: #f6f7fb;
						}
					}

					.c_cnMinus,
					.c_cnAdd {
						width: 52rpx;
						height: 48rpx;
						position: relative;
					}

					.c_cnMinus::before,
					.c_cnAdd::before,
					.c_cnAdd::after {
						content: "";
						width: 24rpx;
						height: 4rpx;
						border-radius: 4rpx;
						background: #333;
						position: absolute;
						top: 50%;
						left: 50%;
						transform: translate(-50%, -50%);
					}

					.c_cnAdd::after {
						width: 4rpx;
						height: 24rpx;
					}
				}
			}

			.imgBox {
				display: grid;
				grid-template-columns: repeat(3, 1fr);
				grid-gap: .5rem;

				.item {
					position: relative;
					width: 200rpx;
					height: 200rpx;
					border-radius: 8rpx;

					.delImg {
						width: 44rpx !important;
						height: 44rpx !important;
						position: absolute;
						top: 0;
						right: 0;
					}

					.imagePath {
						width: 200rpx !important;
						height: 200rpx !important;
						border-radius: 8rpx;
					}

				}

				.upImg {
					width: 200rpx;
					height: 200rpx;
					background-color: #F8F8F8;
					border-radius: 8rpx;
					font: 400 26rpx/40rpx PingFang SC;
					color: #0A0605;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					border: 1px dashed;
					margin-bottom: 80rpx;

					image {
						width: 72rpx;
						height: 72rpx;
					}
				}
			}
		}

		.btn-submit {
			width: 100%;
			height: 98rpx;
			line-height: 98rpx;
			margin-top: 68rpx;
			color: #FFFFFF;
			text-align: center;
			background: linear-gradient(216deg, rgba(254, 210, 98, 0.94), rgba(239, 191, 63, 0.94));
			border-radius: 39rpx;
		}

	}
</style>
